package com.umerclass.ui.home;

import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.lzx.starrysky.StarrySky;
import com.lzx.starrysky.common.PlaybackStage;
import com.lzx.starrysky.provider.SongInfo;
import com.lzx.starrysky.utils.TimerTaskManager;
import com.umerclass.R;
import com.umerclass.frame.model.InfoResult;
import com.umerclass.frame.ui.activity.BaseActivity;
import com.umerclass.frame.ui.barlibrary.ImmersionBar;
import com.umerclass.ui.home.view.PlayPauseView;
import com.umerclass.utils.MusicRequest;

import net.steamcrafted.materialiconlib.MaterialIconView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


/**
 * 音频
 */
public class VoiceActivity extends BaseActivity {

    @BindView(R.id.jz_video)
    ImageView jzVideo;
    @BindView(R.id.progressTv)
    TextView progressTv;
    @BindView(R.id.progressSb)
    SeekBar progressSb;
    @BindView(R.id.durationTv)
    TextView durationTv;
    @BindView(R.id.playModeIv)
    ImageView playModeIv;
    @BindView(R.id.prevPlayIv)
    MaterialIconView prevPlayIv;
    @BindView(R.id.loadingPb)
    ProgressBar loadingPb;
    @BindView(R.id.playPauseIv)
    PlayPauseView playPauseIv;
    @BindView(R.id.nextPlayIv)
    MaterialIconView nextPlayIv;
    @BindView(R.id.playQueueIv)
    MaterialIconView playQueueIv;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_teacher)
    TextView tvTeacher;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.linear_shoucang)
    LinearLayout linearShoucang;
    @BindView(R.id.tab)
    TabLayout tab;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    private List<SongInfo> songInfos = new ArrayList<>();
    private String txt = "播放/暂停";
    private int index = 0;
    private int size = 0;
    private String startTime = "";
    private String endTime = "";
    private TimerTaskManager mTimerTask;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTimerTask.removeUpdateProgressTask();
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .navigationBarDarkIcon(true)
                .navigationBarEnable(true)
                .navigationBarColor(R.color.white)
                .navigationBarDarkIcon(true)
                .init();
    }

    @Override
    public boolean isImmersionBarEnabled() {
        return true;
    }

    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_voice;
    }


    @Override
    public void init() {

       /* Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.white));*/
        //testInfos();

        mTimerTask = new TimerTaskManager();
        //进度更新
        mTimerTask.setUpdateProgressTask(() -> {
            long position = StarrySky.with().getPlayingPosition();
            long duration = StarrySky.with().getDuration();
            long buffered = StarrySky.with().getBufferedPosition();
            if (progressSb.getMax() != duration) {
                progressSb.setMax((int) duration);
            }
            //Log.i("PlayDetailActivity", "duration = " + duration);
            progressSb.setProgress((int) position);
            progressSb.setSecondaryProgress((int) buffered);
            progressTv.setText(formatMusicTime(position));
            durationTv.setText(formatMusicTime(duration));
        });
        //进度条滑动
        progressSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                StarrySky.with().seekTo(seekBar.getProgress());
            }
        });
        //上一首
        prevPlayIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StarrySky.with().skipToPrevious();
            }
        });
        //下一首
        nextPlayIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StarrySky.with().skipToNext();
            }
        });
        playPauseIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(songInfos!=null && songInfos.size()>0){
                    if (txt.equals("播放/暂停")) {
                        playPauseIv.play();
                        StarrySky.with().playMusic(songInfos, 0);
                    } else if (txt.equals("暂停")) {
                        StarrySky.with().pauseMusic();
                        playPauseIv.pause();
                    } else if (txt.equals("播放")) {
                        playPauseIv.play();
                        StarrySky.with().restoreMusic();
                    }
                }else {
                    showToast("没有课程");
                }
            }
        });

        //状态监听
        StarrySky.with().playbackState().observe(this, playbackStage -> {
            if (playbackStage == null) {
                return;
            }
            switch (playbackStage.getStage()) {
                case PlaybackStage.NONE:
                    txt = "播放/暂停";
                    break;
                case PlaybackStage.START:
                    txt = "暂停";
                    mTimerTask.startToUpdateProgress();
                    Glide.with(this).load(songInfos.get(StarrySky.with().getNowPlayingIndex()).getSongCover()).into(jzVideo);
                    break;
                case PlaybackStage.PAUSE:
                    txt = "播放";
                    mTimerTask.startToUpdateProgress();
                    break;
                case PlaybackStage.STOP:
                    txt = "播放";
                    mTimerTask.startToUpdateProgress();
                    break;
                case PlaybackStage.COMPLETION:
                    txt = "播放/暂停";
                    mTimerTask.startToUpdateProgress();
                    break;
                case PlaybackStage.BUFFERING:
                    txt = "缓存中";
                    break;
                case PlaybackStage.ERROR:
                    txt = "播放/暂停";
                    mTimerTask.startToUpdateProgress();
                    break;
                default:
                    break;
            }
        });

        //获取数据
        MusicRequest musicRequest = new MusicRequest();
        musicRequest.getMusicList(this, list -> {
            runOnUiThread(() -> {
                StarrySky.with().updatePlayList(list);
                songInfos.addAll(list);
            });
        });
    }

    @Override
    public void loadData() {

    }

    @Override
    protected void onSuccess(int what, InfoResult t) {

    }

    @Override
    protected void onFail(int what, InfoResult t) {

    }

    private void play() {
    }

    private void next() {
    }

    private void prev() {
    }

    private void testInfos(){

        /**
         * 一个song应该有其id
         */

        SongInfo song = new SongInfo();
        song.setSongId("111");
        song.setSongUrl("http://audio04.dmhmusic.com/71_53_T10052953671_128_4_1_0_sdk-cpm/cn/0209/M00/E1/B8/ChR47F33J_yAHE_JACrgf2qqnyQ634.mp3?xcode=87adccbf4760dea8617084a53b35252f10b375b");
        song.setDuration(200);

        SongInfo song2 = new SongInfo();
        song2.setSongId("222");
        song2.setSongUrl("http://audio04.dmhmusic.com/71_53_T10052953671_128_4_1_0_sdk-cpm/cn/0209/M00/E1/B8/ChR47F33J_yAHE_JACrgf2qqnyQ634.mp3?xcode=7bff957fe7f413646172b9224116ac80e961f12");
        song2.setDuration(175);

        songInfos.add(song);
        songInfos.add(song2);

        StarrySky.with().updatePlayList(songInfos);
    }

    private String formatMusicTime(long duration) {
        String time = "";
        long minute = duration / 60000;
        long seconds = duration % 60000;
        long second = Math.round((int) seconds / 1000);
        if (minute < 10) {
            time += "0";
        }
        time += minute + ":";
        if (second < 10) {
            time += "0";
        }
        time += second;
        return time;
    }

}
